import React from 'react'
import { ScrollView, DeviceEventEmitter, NativeModules, NativeEventEmitter, Modal, StatusBar, FlatList, TouchableOpacity, TouchableHighlight, Alert, Dimensions, StyleSheet, Animated, View, Text, Image, Easing } from 'react-native'
const { width, height } = Dimensions.get('window');

import LinearGradient from 'react-native-linear-gradient'
import {getffly} from '../utils/common';
import screen from '../utils/screen';
import Images from '../images/Images';

var c_deviceWidth = screen.PIXEL_448;
var dislength = 3;
const c_duration = 250;

const showindex = 20;
class SelectionB extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            animationType: 'none',
            modalVisible: false,
            transparent: true,
            bottom: new Animated.Value(0),
            loadstate: 0,
            title: '',
            sublist: [],
            countryid: '',
        }
        this.taget = null;
        this.callback = null;

        this.flatList1 = null;
        this.setFlatList1Ref1 = (element) => {
            this.flatList1 = element;
        };

        this.dqindexID = 1;
        this.allsublist = [];
        this.isFetchload = false;
    }
    componentDidMount = () => {
        const { taget, callback, list } = this.props;
        if (list) {
            this.allsublist = list;
        }
    }
    componentWillUnmount = () => {

    }
    setUI1() {
        this.dqindexID = 1;
        var sublist = [];
        if (this.dqindexID * showindex > this.allsublist.length) {
            sublist = this.allsublist;
        }
        else {
            for (var i = 0; i < this.dqindexID * showindex; i++) {
                if (this.allsublist[i]) {
                    sublist.push(this.allsublist[i]);
                }
            }
        }
        this.setState({
            sublist: sublist,
        }, () => {

        });
    }
    
    showFromBottom() {
        var tarheight = 0;
        Animated.timing(this.state.bottom, {
            toValue: -c_deviceWidth,
            duration: c_duration,
            useNativeDriver: false,
            easing: Easing.linear 
        }).start();
    }
    
    hideFromBottom() {
        var self = this;
        if (this._timer)
            clearInterval(this._timer);
        Animated.timing(this.state.bottom, {
            toValue: 0,
            duration: 0,
            useNativeDriver: false,
            easing: Easing.linear 
        }).start(() => {
            self.flatList1 && self.flatList1.scrollToOffset({ x: 0, y: 0, animated: false })
            self.isFetchload = false;
            self.dqindexID = 1;
            self.allsublist = [];
            self.setUI1();
            self.setState({ modalVisible: false})
        });
    }
    onclick1 = (title1 = "", str1 = "", list1 = []) => {
        if (list1.length > 0) {
            this.allsublist = list1;
            this.setState({
                modalVisible: true,
                countryid: str1,
                title: title1,
            });
        }
        else {
            this.setState({
                modalVisible: true,
                countryid: str1,
                title: title1,
            });
        }
        this.setUI1();
        this.showFromBottom();
    }
    onclick2 = () => {
        this.hideFromBottom();
    }
    _setModalVisible = (visible) => {
        this.setState({ modalVisible: visible });
    }
    create_item = ({ item, index }) => {
        var color1 = "#1C4140";
        if (this.state.countryid === item.name) {
            color1 = "#0DC253";
        }
        return <TouchableOpacity activeOpacity={1.0} onPress={() => {
            if (this.taget && this.callback)
                this.callback.call(this.taget, item);
            this.onclick2();
        }} >
            <View style={{ width: c_deviceWidth, height: screen.PIXEL_80 , flexDirection: 'row', alignItems: 'center'}}>
                <Text style={{fontFamily:getffly("bold"), fontSize: 16 , lineHeight: screen.PIXEL_50 , color: color1, position: 'absolute', left: screen.PIXEL_20  }}>{item.name}</Text>
            </View>
        </TouchableOpacity >
    }
    renderEndComp = () => {
        console.log("renderEndComp");
        if (this.state.loadstate == 0) {
            return <View style={{ flex: 1, height: 32 }}></View>
        }
        else if (this.state.loadstate == 1) {
            return <View style={{ flex: 1, height: 32, alignItems: 'center' }}>
                <Text style={{ fontFamily:getffly("regular"), fontSize: 32 , color: '#rgba(0,0,0,0.35)', lineHeight: 45 , marginTop: 32  }}>
                    {}
                </Text>
            </View>
        }
        else if (this.state.loadstate == 2) {
            return <View style={{ flex: 1, height: 32, alignItems: 'center' }}>
                <Text style={{ fontFamily:getffly("regular"), fontSize: 32 , color: '#rgba(0,0,0,0.35)', lineHeight: 45 , marginTop: 32  }}>
                    {}
                </Text>
            </View>
        }
        else if (this.state.loadstate == 3) {
            return <View style={{ flex: 1, height: 64 + 128 , alignItems: 'center' }}>
                <Text style={{ fontFamily:getffly("regular"), fontSize: 32 , color: '#rgba(0,0,0,0.35)', lineHeight: 45 , marginTop: 32  }}>
                    {}
                </Text>
            </View>
        }
    }
    onEndReached = () => {
        var self = this;
        console.log("onEndReached");
        console.log("onEndReached22::", this.state.sublist.length);
        console.log("onEndReached23::", this.allsublist.length);
        console.log("onEndReached24::", this.isFetchload);
        if (!this.isFetchload) {
            this.isFetchload = true;

            var sublist = [];
            if (this.state.sublist.length < this.allsublist.length) {

                this.dqindexID += 1;
                if (this.dqindexID * showindex > this.allsublist.length) {
                    sublist = this.allsublist;
                }
                else {
                    for (var i = 0; i < this.dqindexID * showindex; i++) {
                        if (this.allsublist[i]) {
                            sublist.push(this.allsublist[i]);
                        }
                    }
                }
                this.setState({
                    loadstate: 2,
                    sublist: sublist
                }, () => {
                    self.isFetchload = false;
                })
            }
            else {
                if (this.state.sublist.length != 0) {
                    if (this.state.sublist.length <= 20) {
                        if (this.state.loadstate != 0) {
                            this.setState({
                                loadstate: 0,
                            });
                        }
                    }
                    else {
                        if (this.state.loadstate != 1) {
                            this.setState({
                                loadstate: 1,
                            });
                        }
                    }
                }
                else {
                    if (this.state.loadstate != 0) {
                        this.setState({
                            loadstate: 0,
                        });
                    }
                }
            }
        } else {


        }
    }
    render() {
        const { taget, callback, list } = this.props;
        this.taget = taget;
        this.callback = callback;
        return (
            <Modal
                animationType={this.state.animationType}
                transparent={this.state.transparent}
                visible={this.state.modalVisible}
                onRequestClose={() => { this._setModalVisible(false) }}
                onShow={this.startShow}
            >
                <StatusBar barStyle='light-content' translucent={true} backgroundColor="rgba(16, 17, 22,0.75)" animated={false} />
                <TouchableOpacity activeOpacity={1.0} onPress={() => { }} style={styles.bottomcontainer}>
                    <Animated.View style={[styles.bottomcontainer1, {left: width, transform: [{ translateX: this.state.bottom }] }]}>
                        <View style={{ width: width, height: screen.statusBarHeight}}></View>
                        <View style={{ flex: 1 }}>
                            <FlatList
                                extraData={this.state}
                                showsVerticalScrollIndicator={false}
                                data={this.state.sublist}
                                renderItem={this.create_item.bind(this)}
                                style={styles.list}
                                ListFooterComponent={this.renderEndComp}
                                keyExtractor={(item, index) => index.toString()}
                                onEndReached={this.onEndReached}
                                onEndReachedThreshold={0.2}
                                ref={this.setFlatList1Ref1}
                            />
                        </View>
                    </Animated.View>
                </TouchableOpacity>
                <TouchableOpacity activeOpacity={1.0} style={{position:'absolute',left:0,zIndex: 3,}} onPress={() => {
                    this.hideFromBottom();
                 }}>
                    <View style={{width:width - c_deviceWidth,height:height}}>
                        
                    </View>
                </TouchableOpacity>
            </Modal>
        )
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#0F0525',
        flexDirection: 'column',
        alignItems: 'center'
    },

    bottomcontainer: {
        zIndex: 2,
        flex: 1,
        alignItems: 'center',
        backgroundColor: 'rgba(16, 17, 22,0.75)',
        justifyContent: 'flex-end',
    },
    bottomcontainer1: {
        zIndex: 3,
        width: c_deviceWidth,
        height: height,
        backgroundColor: '#FFFFFF',
        // backgroundColor:'red',
        position: 'absolute',
        bottom: 0,
        left:width,
        // bottom:0,
        alignItems: 'center',
        flexDirection: 'column'
        // transform: [{translateY:-c_deviceHeight}]
    },
});
SelectionB.navigationOptions = {
    title: null, 
    headerLeft: () => null,
    headerShown: false,
};
export default SelectionB;
